import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import sqlite3
from datetime import datetime, date, timedelta
import threading
import time
import os
import sys
from plyer import notification
import hashlib
import base64
from cryptography.fernet import Fernet
import json
import ntplib
import webbrowser
import winreg
import subprocess


class TaxRecorderApp:
    def __init__(self, root):
        self.root = root
        self.root.title("自企所得税税种记录器")
        self.root.geometry("1200x700")
        self.root.configure(bg="#0f1419")
        
        # 获取程序所在目录（兼容PyInstaller打包）
        if getattr(sys, 'frozen', False):
            # 如果是打包后的exe
            self.app_dir = os.path.dirname(sys.executable)
        else:
            # 如果是直接运行的py文件
            self.app_dir = os.path.dirname(os.path.abspath(__file__))
        
        # 密码文件路径
        self.password_file = os.path.join(self.app_dir, "tax.dll")
        
        # 自校验文件路径
        self.self_check_file = os.path.join(self.app_dir, "base.ycyt")
        # 执行自校验，失败则终止启动
        if not self.self_check():
            return
        
        # 网络环境检查，失败则终止启动
        if not self.check_network_environment():
            return
        
        # NTP 时间同步状态
        self.ntp_time = None
        self.ntp_offset = 0
        self.use_ntp = True
        
        # 初始化数据库
        self.init_database()
        
        # 启动报税提醒检查线程
        self.start_reminder_thread()
        
        self.setup_ui()
        self.load_companies()
        
        # UI创建完成后启动NTP时间同步
        self.start_ntp_sync()
        
        # 启动时间显示更新
        self.update_time_display()
    
    def init_database(self):
        """初始化数据库"""
        db_path = os.path.join(self.app_dir, "tax_data.db")
        self.conn = sqlite3.connect(db_path, check_same_thread=False)
        self.cursor = self.conn.cursor()
        
        # 创建公司表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS companies (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL UNIQUE,
                contact TEXT,
                phone TEXT,
                address TEXT,
                created_date TEXT DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # 创建税种表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS tax_types (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                company_id INTEGER,
                tax_name TEXT NOT NULL,
                tax_code TEXT,
                tax_rate TEXT,
                filing_period TEXT,
                deadline_day INTEGER,
                last_filed_date TEXT,
                notes TEXT,
                FOREIGN KEY (company_id) REFERENCES companies (id)
            )
        ''')
        
        # 创建报税提醒记录表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS reminder_logs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                company_id INTEGER,
                tax_type_id INTEGER,
                remind_date TEXT,
                status TEXT,
                FOREIGN KEY (company_id) REFERENCES companies (id),
                FOREIGN KEY (tax_type_id) REFERENCES tax_types (id)
            )
        ''')
        
        # 创建责令书表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS correction_orders (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                company_id INTEGER,
                order_number TEXT,
                issue_date TEXT,
                deadline_date TEXT,
                content TEXT,
                status TEXT DEFAULT '未办理',
                notes TEXT,
                created_date TEXT DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (company_id) REFERENCES companies (id)
            )
        ''')
        
        self.conn.commit()
    
    def self_check(self):
        """自校验方法，验证 base.ycyt 文件"""
        def _show_security_block():
            try:
                messagebox.showerror("安全提示", "为安全考虑Windows程序无法启动，请您联系管理员，管理员微信：cnetsteam-langmeng")
            except Exception:
                pass
            try:
                self.root.after(100, self.root.destroy)
            except Exception:
                pass
        
        def _get_self_check_key():
            secret = b"ycyt-2025-cnetsteam-langmeng"
            return base64.urlsafe_b64encode(hashlib.sha256(secret).digest())
        
        def _read_self_check(path):
            with open(path, 'rb') as f:
                return f.read()
        
        def _verify_payload(payload_bytes):
            key = _get_self_check_key()
            fernet = Fernet(key)
            try:
                decoded = fernet.decrypt(payload_bytes)
                data = json.loads(decoded.decode('utf-8'))
                # 需要包含固定校验码及绑定目录
                if not isinstance(data, dict):
                    return False
                if data.get('code') != 'YCT-SELF-CHECK':
                    return False
                if data.get('dir') != self.app_dir:
                    return False
                return True
            except Exception:
                return False
        
        try:
            # 确认文件存在
            if not os.path.exists(self.self_check_file):
                _show_security_block()
                return False
            payload = _read_self_check(self.self_check_file)
            if not _verify_payload(payload):
                _show_security_block()
                return False
            return True
        except Exception:
            _show_security_block()
            return False
    
    def check_network_environment(self):
        """检查网络环境，显示进度条，检测代理和VPN"""
        # 创建进度窗口
        progress_window = tk.Toplevel(self.root)
        progress_window.title("网络环境检查")
        progress_window.geometry("500x200")
        progress_window.configure(bg="#1a2332")
        progress_window.resizable(False, False)
        progress_window.transient(self.root)
        progress_window.grab_set()
        
        # 禁止关闭按钮
        progress_window.protocol("WM_DELETE_WINDOW", lambda: None)
        
        # 居中显示
        progress_window.update_idletasks()
        x = (progress_window.winfo_screenwidth() // 2) - (500 // 2)
        y = (progress_window.winfo_screenheight() // 2) - (200 // 2)
        progress_window.geometry(f"500x200+{x}+{y}")
        
        # 标题
        title_label = tk.Label(
            progress_window,
            text="正在检查网络环境...",
            font=("Microsoft YaHei UI", 14, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        )
        title_label.pack(pady=20)
        
        # 进度条
        progress = ttk.Progressbar(
            progress_window,
            length=400,
            mode='determinate',
            maximum=100
        )
        progress.pack(pady=10)
        
        # 状态标签
        status_label = tk.Label(
            progress_window,
            text="准备开始检查...",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#ffffff"
        )
        status_label.pack(pady=10)
        
        # 检查结果
        check_result = {'passed': True, 'reason': ''}
        
        def check_proxy():
            """检查系统代理设置"""
            try:
                # 检查注册表中的代理设置
                with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                   r'Software\Microsoft\Windows\CurrentVersion\Internet Settings') as key:
                    proxy_enable = winreg.QueryValueEx(key, 'ProxyEnable')[0]
                    if proxy_enable == 1:
                        return True
            except Exception:
                pass
            return False
        
        def check_vpn():
            """检查VPN连接"""
            try:
                # 使用 rasdial 命令检查活动的拨号连接
                result = subprocess.run(
                    ['rasdial'],
                    capture_output=True,
                    text=True,
                    timeout=3,
                    creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
                )
                # 如果输出包含连接信息，说明有VPN连接
                if result.stdout and '没有连接' not in result.stdout and 'No connections' not in result.stdout:
                    if result.stdout.strip() and len(result.stdout.strip()) > 10:
                        return True
                
                # 检查网络适配器中的VPN接口
                result = subprocess.run(
                    ['netsh', 'interface', 'show', 'interface'],
                    capture_output=True,
                    text=True,
                    encoding='gbk',
                    timeout=3,
                    creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == 'win32' else 0
                )
                # 检查常见VPN关键字
                vpn_keywords = ['VPN', 'TAP-Windows', 'TUN', 'Tunnel', 'OpenVPN', 'WireGuard', 'L2TP', 'PPTP']
                lines = result.stdout.split('\n')
                for line in lines:
                    if '已连接' in line or 'Connected' in line:
                        for keyword in vpn_keywords:
                            if keyword.lower() in line.lower():
                                return True
            except Exception:
                pass
            return False
        
        def step1_check_proxy():
            """步骤1：检查代理"""
            status_label.config(text="正在检查系统代理设置...")
            progress['value'] = 10
            progress_window.update()
            
            # 在后台线程执行检查
            def do_check():
                result = check_proxy()
                progress_window.after(0, lambda: step1_complete(result))
            
            threading.Thread(target=do_check, daemon=True).start()
        
        def step1_complete(has_proxy):
            """步骤1完成"""
            progress['value'] = 40
            progress_window.update()
            
            if has_proxy:
                check_result['passed'] = False
                check_result['reason'] = 'proxy'
                finish_check()
            else:
                # 继续下一步
                progress_window.after(200, step2_check_vpn)
        
        def step2_check_vpn():
            """步骤2：检查VPN"""
            status_label.config(text="正在检查VPN连接状态...")
            progress['value'] = 50
            progress_window.update()
            
            # 在后台线程执行检查
            def do_check():
                result = check_vpn()
                progress_window.after(0, lambda: step2_complete(result))
            
            threading.Thread(target=do_check, daemon=True).start()
        
        def step2_complete(has_vpn):
            """步骤2完成"""
            progress['value'] = 90
            progress_window.update()
            
            if has_vpn:
                check_result['passed'] = False
                check_result['reason'] = 'vpn'
            
            # 完成检查
            progress_window.after(200, finish_check)
        
        def finish_check():
            """完成检查"""
            progress['value'] = 100
            
            if check_result['passed']:
                status_label.config(text="网络环境检查通过 ✓", fg="#00ff88")
            else:
                status_label.config(text="检测到网络异常 ✗", fg="#ff4757")
            
            progress_window.update()
            progress_window.after(500, progress_window.destroy)
        
        # 延迟启动检查，确保窗口完全显示
        progress_window.after(100, step1_check_proxy)
        
        # 等待检查完成
        progress_window.wait_window()
        
        # 处理检查结果
        if not check_result['passed']:
            messagebox.showerror(
                "网络环境错误",
                "您的网络环境出现错误，请检查系统网络代理是否是关闭状态！"
            )
            try:
                self.root.after(100, self.root.destroy)
            except Exception:
                pass
            return False
        
        return True
    def setup_ui(self):
        # 主标题
        title_frame = tk.Frame(self.root, bg="#1a2332", pady=15)
        title_frame.pack(fill=tk.X)
        
        title_label = tk.Label(
            title_frame,
            text="自企所得税税种记录器",
            font=("Microsoft YaHei UI", 22, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        )
        title_label.pack()
        
        subtitle_label = tk.Label(
            title_frame,
            text="张家口市蔚县音创云图互联网有限公司",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#66ccff"
        )
        subtitle_label.pack()
        
        # 时间显示
        self.time_label = tk.Label(
            title_frame,
            text="",
            font=("Microsoft YaHei UI", 11),
            bg="#1a2332",
            fg="#00ff88"
        )
        self.time_label.pack(pady=(5, 0))
        
        # 主容器
        main_container = tk.Frame(self.root, bg="#0f1419")
        main_container.pack(fill=tk.BOTH, expand=True, padx=15, pady=10)
        
        # 左侧面板 - 公司列表
        left_panel = tk.Frame(main_container, bg="#0f1419")
        left_panel.pack(side=tk.LEFT, fill=tk.BOTH, padx=(0, 10))
        
        # 公司列表标题
        company_title = tk.Label(
            left_panel,
            text="📋 公司列表",
            font=("Microsoft YaHei UI", 14, "bold"),
            bg="#0f1419",
            fg="#00d4ff"
        )
        company_title.pack(pady=(0, 10))
        
        # 公司列表框
        list_frame = tk.Frame(left_panel, bg="#1a2332", relief=tk.RIDGE, bd=2)
        list_frame.pack(fill=tk.BOTH, expand=True)
        
        scrollbar = tk.Scrollbar(list_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.company_listbox = tk.Listbox(
            list_frame,
            font=("Microsoft YaHei UI", 11),
            bg="#1a2332",
            fg="#ffffff",
            selectbackground="#00d4ff",
            selectforeground="#000000",
            yscrollcommand=scrollbar.set,
            relief=tk.FLAT,
            height=20,
            width=30
        )
        self.company_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.company_listbox.yview)
        self.company_listbox.bind('<<ListboxSelect>>', self.on_company_select)
        
        # 公司操作按钮
        company_btn_frame = tk.Frame(left_panel, bg="#0f1419", pady=10)
        company_btn_frame.pack(fill=tk.X)
        
        add_company_btn = tk.Button(
            company_btn_frame,
            text="➕ 添加公司",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.add_company
        )
        add_company_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        del_company_btn = tk.Button(
            company_btn_frame,
            text="🗑 删除公司",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.delete_company
        )
        del_company_btn.pack(side=tk.LEFT)
        
        # 密码管理按钮（第二行）
        password_btn_frame = tk.Frame(left_panel, bg="#0f1419", pady=5)
        password_btn_frame.pack(fill=tk.X)
        
        password_mgr_btn = tk.Button(
            password_btn_frame,
            text="🔐 密码管理",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#6c5ce7",
            fg="#ffffff",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.open_password_manager
        )
        password_mgr_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        # 责令书管理按钮
        order_mgr_btn = tk.Button(
            password_btn_frame,
            text="📋 责令书管理",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#fd79a8",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.open_order_manager
        )
        order_mgr_btn.pack(side=tk.LEFT)
        
        # 右侧面板 - 税种管理
        right_panel = tk.Frame(main_container, bg="#0f1419")
        right_panel.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 税种标题
        tax_title = tk.Label(
            right_panel,
            text="📊 税种管理",
            font=("Microsoft YaHei UI", 14, "bold"),
            bg="#0f1419",
            fg="#00d4ff"
        )
        tax_title.pack(pady=(0, 10))
        
        # 税种列表
        tax_list_frame = tk.Frame(right_panel, bg="#1a2332", relief=tk.RIDGE, bd=2)
        tax_list_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建树形视图
        columns = ("税种名称", "税种编码", "税率", "申报周期", "截止日期", "最后申报")
        self.tax_tree = ttk.Treeview(tax_list_frame, columns=columns, show="tree headings", height=15)
        
        # 定义列
        self.tax_tree.column("#0", width=50)
        self.tax_tree.heading("#0", text="ID")
        
        for col in columns:
            self.tax_tree.column(col, width=120, anchor=tk.CENTER)
            self.tax_tree.heading(col, text=col)
        
        # 滚动条
        tax_scrollbar = ttk.Scrollbar(tax_list_frame, orient=tk.VERTICAL, command=self.tax_tree.yview)
        self.tax_tree.configure(yscrollcommand=tax_scrollbar.set)
        
        self.tax_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        tax_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 配置树形视图样式
        style = ttk.Style()
        style.theme_use("clam")
        style.configure("Treeview",
                       background="#1a2332",
                       foreground="#ffffff",
                       fieldbackground="#1a2332",
                       borderwidth=0)
        style.configure("Treeview.Heading",
                       background="#00d4ff",
                       foreground="#000000",
                       relief=tk.FLAT)
        style.map("Treeview", background=[("selected", "#00d4ff")])
        
        # 税种操作按钮
        tax_btn_frame = tk.Frame(right_panel, bg="#0f1419", pady=10)
        tax_btn_frame.pack(fill=tk.X)
        
        add_tax_btn = tk.Button(
            tax_btn_frame,
            text="➕ 添加税种",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.add_tax_type
        )
        add_tax_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        edit_tax_btn = tk.Button(
            tax_btn_frame,
            text="✏ 编辑税种",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#ffa502",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.edit_tax_type
        )
        edit_tax_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        del_tax_btn = tk.Button(
            tax_btn_frame,
            text="🗑 删除税种",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.delete_tax_type
        )
        del_tax_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        # 更新申报时间按钮
        update_filed_btn = tk.Button(
            tax_btn_frame,
            text="📅 更新申报时间",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#26de81",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.update_filed_date
        )
        update_filed_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        # 季度计算器按钮
        quarter_calc_btn = tk.Button(
            tax_btn_frame,
            text="🧮 季度计算器",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#fd79a8",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.show_quarter_calculator
        )
        quarter_calc_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        reminder_btn = tk.Button(
            tax_btn_frame,
            text="🔔 测试提醒",
            font=("Microsoft YaHei UI", 10, "bold"),
            bg="#a29bfe",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=15,
            pady=8,
            command=self.test_reminder
        )
        reminder_btn.pack(side=tk.LEFT)
        
        # 状态栏
        status_frame = tk.Frame(self.root, bg="#1a2332", pady=8)
        status_frame.pack(fill=tk.X, side=tk.BOTTOM)
        
        self.status_label = tk.Label(
            status_frame,
            text="就绪",
            font=("Microsoft YaHei UI", 9),
            bg="#1a2332",
            fg="#ffffff",
            anchor=tk.W
        )
        self.status_label.pack(side=tk.LEFT, padx=20)
    
    def load_companies(self):
        """加载公司列表"""
        self.company_listbox.delete(0, tk.END)
        self.cursor.execute("SELECT id, name FROM companies ORDER BY name")
        companies = self.cursor.fetchall()
        
        for company in companies:
            self.company_listbox.insert(tk.END, f"{company[1]}")
            self.company_listbox.itemconfig(tk.END, {'fg': '#ffffff'})
        
        self.status_label.config(text=f"已加载 {len(companies)} 家公司")
    
    def on_company_select(self, event):
        """公司选择事件"""
        selection = self.company_listbox.curselection()
        if not selection:
            return
        
        company_name = self.company_listbox.get(selection[0])
        self.load_tax_types(company_name)
    
    def load_tax_types(self, company_name):
        """加载税种列表"""
        # 清空树形视图
        for item in self.tax_tree.get_children():
            self.tax_tree.delete(item)
        
        # 获取公司ID
        self.cursor.execute("SELECT id FROM companies WHERE name=?", (company_name,))
        result = self.cursor.fetchone()
        if not result:
            return
        
        company_id = result[0]
        
        # 获取税种列表
        self.cursor.execute("""
            SELECT id, tax_name, tax_code, tax_rate, filing_period, deadline_day, last_filed_date
            FROM tax_types WHERE company_id=?
        """, (company_id,))
        
        tax_types = self.cursor.fetchall()
        
        for tax in tax_types:
            self.tax_tree.insert("", tk.END, text=tax[0], values=(
                tax[1],  # 税种名称
                tax[2] or "",  # 税种编码
                tax[3] or "",  # 税率
                tax[4] or "",  # 申报周期
                f"{tax[5]}日" if tax[5] else "",  # 截止日期
                tax[6] or "未申报"  # 最后申报日期
            ))
        
        self.status_label.config(text=f"{company_name} - 共 {len(tax_types)} 个税种")
    
    def add_company(self):
        """添加公司"""
        dialog = tk.Toplevel(self.root)
        dialog.title("添加公司")
        dialog.geometry("500x400")
        dialog.configure(bg="#1a2332")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单
        form_frame = tk.Frame(dialog, bg="#1a2332", padx=30, pady=20)
        form_frame.pack(fill=tk.BOTH, expand=True)
        
        fields = [
            ("公司名称*", "name"),
            ("联系人", "contact"),
            ("联系电话", "phone"),
            ("公司地址", "address")
        ]
        
        entries = {}
        
        for i, (label, field) in enumerate(fields):
            tk.Label(
                form_frame,
                text=label,
                font=("Microsoft YaHei UI", 11),
                bg="#1a2332",
                fg="#00d4ff",
                anchor=tk.W
            ).grid(row=i, column=0, sticky=tk.W, pady=10)
            
            entry = tk.Entry(
                form_frame,
                font=("Microsoft YaHei UI", 11),
                bg="#0f1419",
                fg="#ffffff",
                insertbackground="#00d4ff",
                relief=tk.FLAT,
                width=30
            )
            entry.grid(row=i, column=1, pady=10, padx=10)
            entries[field] = entry
        
        # 按钮
        btn_frame = tk.Frame(dialog, bg="#1a2332", pady=10)
        btn_frame.pack(fill=tk.X)
        
        def save_company():
            name = entries["name"].get().strip()
            if not name:
                messagebox.showwarning("警告", "请输入公司名称！")
                return
            
            try:
                self.cursor.execute("""
                    INSERT INTO companies (name, contact, phone, address)
                    VALUES (?, ?, ?, ?)
                """, (
                    name,
                    entries["contact"].get().strip(),
                    entries["phone"].get().strip(),
                    entries["address"].get().strip()
                ))
                self.conn.commit()
                messagebox.showinfo("成功", f"公司 {name} 添加成功！")
                self.load_companies()
                dialog.destroy()
            except sqlite3.IntegrityError:
                messagebox.showerror("错误", "该公司名称已存在！")
        
        tk.Button(
            btn_frame,
            text="💾 保存",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=30,
            pady=8,
            command=save_company
        ).pack(side=tk.LEFT, padx=20)
        
        tk.Button(
            btn_frame,
            text="❌ 取消",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            relief=tk.FLAT,
            padx=30,
            pady=8,
            command=dialog.destroy
        ).pack(side=tk.LEFT)
    
    def delete_company(self):
        """删除公司"""
        selection = self.company_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请先选择要删除的公司！")
            return
        
        company_name = self.company_listbox.get(selection[0])
        
        if messagebox.askyesno("确认删除", f"确定要删除公司 {company_name} 及其所有税种记录吗？"):
            self.cursor.execute("SELECT id FROM companies WHERE name=?", (company_name,))
            result = self.cursor.fetchone()
            if result:
                company_id = result[0]
                self.cursor.execute("DELETE FROM tax_types WHERE company_id=?", (company_id,))
                self.cursor.execute("DELETE FROM companies WHERE id=?", (company_id,))
                self.conn.commit()
                messagebox.showinfo("成功", f"公司 {company_name} 已删除！")
                self.load_companies()
                # 清空税种列表
                for item in self.tax_tree.get_children():
                    self.tax_tree.delete(item)
    
    def add_tax_type(self):
        """添加税种"""
        selection = self.company_listbox.curselection()
        if not selection:
            messagebox.showwarning("警告", "请先选择公司！")
            return
        
        company_name = self.company_listbox.get(selection[0])
        self.show_tax_dialog(company_name)
    
    def show_tax_dialog(self, company_name, tax_data=None):
        """显示税种编辑对话框"""
        dialog = tk.Toplevel(self.root)
        dialog.title("添加税种" if not tax_data else "编辑税种")
        dialog.geometry("550x550")
        dialog.configure(bg="#1a2332")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 表单
        form_frame = tk.Frame(dialog, bg="#1a2332", padx=30, pady=20)
        form_frame.pack(fill=tk.BOTH, expand=True)
        
        tk.Label(
            form_frame,
            text=f"公司: {company_name}",
            font=("Microsoft YaHei UI", 12, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=0, column=0, columnspan=2, pady=(0, 20))
        
        fields = [
            ("税种名称*", "tax_name", "entry"),
            ("税种编码", "tax_code", "entry"),
            ("税率", "tax_rate", "entry"),
            ("申报周期*", "filing_period", "combo"),
            ("截止日期(日)*", "deadline_day", "entry"),
            ("备注", "notes", "text")
        ]
        
        entries = {}
        
        for i, (label, field, widget_type) in enumerate(fields, start=1):
            tk.Label(
                form_frame,
                text=label,
                font=("Microsoft YaHei UI", 10),
                bg="#1a2332",
                fg="#00d4ff",
                anchor=tk.W
            ).grid(row=i, column=0, sticky=tk.W, pady=8)
            
            if widget_type == "combo":
                widget = ttk.Combobox(
                    form_frame,
                    font=("Microsoft YaHei UI", 10),
                    values=["月报", "季报", "年报"],
                    state="readonly",
                    width=28
                )
                if tax_data:
                    widget.set(tax_data[3] if tax_data[3] else "")
                else:
                    widget.set("月报")
            elif widget_type == "text":
                widget = tk.Text(
                    form_frame,
                    font=("Microsoft YaHei UI", 10),
                    bg="#0f1419",
                    fg="#ffffff",
                    insertbackground="#00d4ff",
                    relief=tk.FLAT,
                    width=30,
                    height=4
                )
                if tax_data and tax_data[7]:
                    widget.insert("1.0", tax_data[7])
            else:
                widget = tk.Entry(
                    form_frame,
                    font=("Microsoft YaHei UI", 10),
                    bg="#0f1419",
                    fg="#ffffff",
                    insertbackground="#00d4ff",
                    relief=tk.FLAT,
                    width=30
                )
                if tax_data:
                    if field == "tax_name":
                        widget.insert(0, tax_data[0])
                    elif field == "tax_code":
                        widget.insert(0, tax_data[1] or "")
                    elif field == "tax_rate":
                        widget.insert(0, tax_data[2] or "")
                    elif field == "deadline_day":
                        widget.insert(0, str(tax_data[4]) if tax_data[4] else "")
            
            widget.grid(row=i, column=1, pady=8, padx=10)
            entries[field] = widget
        
        # 按钮
        btn_frame = tk.Frame(dialog, bg="#1a2332", pady=10)
        btn_frame.pack(fill=tk.X)
        
        def save_tax():
            tax_name = entries["tax_name"].get().strip()
            filing_period = entries["filing_period"].get()
            deadline_day = entries["deadline_day"].get().strip()
            
            if not tax_name or not filing_period or not deadline_day:
                messagebox.showwarning("警告", "请填写必填项（带*号）！")
                return
            
            try:
                deadline_day = int(deadline_day)
                if deadline_day < 1 or deadline_day > 31:
                    raise ValueError
            except ValueError:
                messagebox.showerror("错误", "截止日期必须是1-31之间的数字！")
                return
            
            # 获取公司ID
            self.cursor.execute("SELECT id FROM companies WHERE name=?", (company_name,))
            company_id = self.cursor.fetchone()[0]
            
            notes_text = entries["notes"].get("1.0", tk.END).strip()
            
            if tax_data:  # 编辑模式
                self.cursor.execute("""
                    UPDATE tax_types SET
                        tax_name=?, tax_code=?, tax_rate=?, filing_period=?,
                        deadline_day=?, notes=?
                    WHERE id=?
                """, (
                    tax_name,
                    entries["tax_code"].get().strip(),
                    entries["tax_rate"].get().strip(),
                    filing_period,
                    deadline_day,
                    notes_text,
                    tax_data[8]  # tax_id
                ))
            else:  # 添加模式
                self.cursor.execute("""
                    INSERT INTO tax_types 
                    (company_id, tax_name, tax_code, tax_rate, filing_period, deadline_day, notes)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                """, (
                    company_id,
                    tax_name,
                    entries["tax_code"].get().strip(),
                    entries["tax_rate"].get().strip(),
                    filing_period,
                    deadline_day,
                    notes_text
                ))
            
            self.conn.commit()
            messagebox.showinfo("成功", "税种保存成功！")
            self.load_tax_types(company_name)
            dialog.destroy()
        
        tk.Button(
            btn_frame,
            text="💾 保存",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=30,
            pady=8,
            command=save_tax
        ).pack(side=tk.LEFT, padx=20)
        
        tk.Button(
            btn_frame,
            text="❌ 取消",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            relief=tk.FLAT,
            padx=30,
            pady=8,
            command=dialog.destroy
        ).pack(side=tk.LEFT)
    
    def edit_tax_type(self):
        """编辑税种"""
        selection = self.tax_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择要编辑的税种！")
            return
        
        company_selection = self.company_listbox.curselection()
        if not company_selection:
            return
        
        company_name = self.company_listbox.get(company_selection[0])
        
        # 获取选中的税种数据
        item = self.tax_tree.item(selection[0])
        tax_id = item['text']
        values = item['values']
        
        # 获取完整税种信息
        self.cursor.execute("""
            SELECT tax_name, tax_code, tax_rate, filing_period, deadline_day, 
                   last_filed_date, notes, id
            FROM tax_types WHERE id=?
        """, (tax_id,))
        tax_data = self.cursor.fetchone()
        
        if tax_data:
            # tax_data: (tax_name, tax_code, tax_rate, filing_period, deadline_day, last_filed_date, notes, id)
            self.show_tax_dialog(company_name, tax_data + (tax_id,))
    
    def delete_tax_type(self):
        """删除税种"""
        selection = self.tax_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择要删除的税种！")
            return
        
        item = self.tax_tree.item(selection[0])
        tax_id = item['text']
        tax_name = item['values'][0]
        
        if messagebox.askyesno("确认删除", f"确定要删除税种 {tax_name} 吗？"):
            self.cursor.execute("DELETE FROM tax_types WHERE id=?", (tax_id,))
            self.conn.commit()
            messagebox.showinfo("成功", f"税种 {tax_name} 已删除！")
            
            company_selection = self.company_listbox.curselection()
            if company_selection:
                company_name = self.company_listbox.get(company_selection[0])
                self.load_tax_types(company_name)
    
    def update_filed_date(self):
        """更新最后申报时间"""
        selection = self.tax_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择要更新的税种！")
            return
        
        item = self.tax_tree.item(selection[0])
        tax_id = item['text']
        tax_name = item['values'][0]
        
        # 创建日期选择对话框
        dialog = tk.Toplevel(self.root)
        dialog.title(f"更新申报时间 - {tax_name}")
        dialog.geometry("400x250")
        dialog.configure(bg="#1a2332")
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 标题
        tk.Label(
            dialog,
            text=f"税种: {tax_name}",
            font=("Microsoft YaHei UI", 13, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).pack(pady=20)
        
        # 日期选择框架
        date_frame = tk.Frame(dialog, bg="#1a2332", padx=30)
        date_frame.pack(pady=10)
        
        # 年份
        tk.Label(
            date_frame,
            text="年份:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=0, column=0, padx=5)
        
        current_year = datetime.now().year
        year_var = tk.StringVar(value=str(current_year))
        year_spinbox = tk.Spinbox(
            date_frame,
            from_=2020,
            to=2050,
            textvariable=year_var,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            relief=tk.FLAT,
            width=8
        )
        year_spinbox.grid(row=0, column=1, padx=5)
        
        # 月份
        tk.Label(
            date_frame,
            text="月份:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=0, column=2, padx=5)
        
        current_month = datetime.now().month
        month_var = tk.StringVar(value=str(current_month))
        month_spinbox = tk.Spinbox(
            date_frame,
            from_=1,
            to=12,
            textvariable=month_var,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            relief=tk.FLAT,
            width=6
        )
        month_spinbox.grid(row=0, column=3, padx=5)
        
        # 日期
        tk.Label(
            date_frame,
            text="日期:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=1, column=0, padx=5, pady=10)
        
        current_day = datetime.now().day
        day_var = tk.StringVar(value=str(current_day))
        day_spinbox = tk.Spinbox(
            date_frame,
            from_=1,
            to=31,
            textvariable=day_var,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            relief=tk.FLAT,
            width=6
        )
        day_spinbox.grid(row=1, column=1, padx=5, pady=10)
        
        # 快捷按钮 - 设置为今天
        tk.Button(
            date_frame,
            text="📅 设为今天",
            font=("Microsoft YaHei UI", 9),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=10,
            pady=5,
            command=lambda: [
                year_var.set(str(datetime.now().year)),
                month_var.set(str(datetime.now().month)),
                day_var.set(str(datetime.now().day))
            ]
        ).grid(row=1, column=2, columnspan=2, padx=5, pady=10)
        
        # 按钮
        btn_frame = tk.Frame(dialog, bg="#1a2332", pady=20)
        btn_frame.pack()
        
        def save_date():
            try:
                year = int(year_var.get())
                month = int(month_var.get())
                day = int(day_var.get())
                
                # 验证日期
                filed_date = date(year, month, day)
                date_str = filed_date.strftime("%Y-%m-%d")
                
                # 更新数据库
                self.cursor.execute(
                    "UPDATE tax_types SET last_filed_date=? WHERE id=?",
                    (date_str, tax_id)
                )
                self.conn.commit()
                
                messagebox.showinfo("成功", f"已将 {tax_name} 的最后申报时间更新为 {date_str}")
                
                # 刷新税种列表
                company_selection = self.company_listbox.curselection()
                if company_selection:
                    company_name = self.company_listbox.get(company_selection[0])
                    self.load_tax_types(company_name)
                
                dialog.destroy()
                
            except ValueError as e:
                messagebox.showerror("错误", f"日期无效：{str(e)}")
        
        tk.Button(
            btn_frame,
            text="💾 保存",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=30,
            pady=8,
            command=save_date
        ).pack(side=tk.LEFT, padx=10)
        
        tk.Button(
            btn_frame,
            text="❌ 取消",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            relief=tk.FLAT,
            padx=30,
            pady=8,
            command=dialog.destroy
        ).pack(side=tk.LEFT, padx=10)
    
    def show_quarter_calculator(self):
        """显示季度计算器"""
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("季度计算器 - 下次申报时间")
        dialog.geometry("900x600")
        dialog.configure(bg="#0f1419")
        dialog.transient(self.root)
        
        # 标题
        title_frame = tk.Frame(dialog, bg="#1a2332", pady=15)
        title_frame.pack(fill=tk.X)
        
        tk.Label(
            title_frame,
            text="🧮 季度计算器",
            font=("Microsoft YaHei UI", 16, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).pack()
        
        tk.Label(
            title_frame,
            text="根据最后申报时间计算下次申报时间",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#66ccff"
        ).pack()
        
        # 主内容区域
        content_frame = tk.Frame(dialog, bg="#0f1419")
        content_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 创建滚动文本区域
        text_widget = scrolledtext.ScrolledText(
            content_frame,
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#ffffff",
            wrap=tk.WORD,
            relief=tk.FLAT,
            padx=15,
            pady=15
        )
        text_widget.pack(fill=tk.BOTH, expand=True)
        
        # 配置标签样式
        text_widget.tag_config("company_title", foreground="#00d4ff", font=("Microsoft YaHei UI", 13, "bold"))
        text_widget.tag_config("tax_name", foreground="#26de81", font=("Microsoft YaHei UI", 11, "bold"))
        text_widget.tag_config("normal", foreground="#ffffff", font=("Microsoft YaHei UI", 10))
        text_widget.tag_config("warning", foreground="#ffa502", font=("Microsoft YaHei UI", 10))
        text_widget.tag_config("overdue", foreground="#ff4757", font=("Microsoft YaHei UI", 10, "bold"))
        text_widget.tag_config("separator", foreground="#66ccff")
        
        # 获取所有公司和税种数据
        self.cursor.execute("SELECT id, name FROM companies ORDER BY name")
        companies = self.cursor.fetchall()
        
        if not companies:
            text_widget.insert(tk.END, "⚠️ 暂无公司数据，请先添加公司。\n", "warning")
        else:
            today = date.today()
            
            for company_id, company_name in companies:
                # 公司标题
                text_widget.insert(tk.END, f"\n{'='*60}\n", "separator")
                text_widget.insert(tk.END, f"🏢 {company_name}\n", "company_title")
                text_widget.insert(tk.END, f"{'='*60}\n\n", "separator")
                
                # 获取该公司的所有税种
                self.cursor.execute("""
                    SELECT tax_name, filing_period, deadline_day, last_filed_date
                    FROM tax_types
                    WHERE company_id=?
                    ORDER BY filing_period, tax_name
                """, (company_id,))
                
                tax_types = self.cursor.fetchall()
                
                if not tax_types:
                    text_widget.insert(tk.END, "  ⚠️ 该公司暂无税种记录\n\n", "warning")
                    continue
                
                for tax_name, filing_period, deadline_day, last_filed_date in tax_types:
                    text_widget.insert(tk.END, f"  📄 {tax_name}\n", "tax_name")
                    text_widget.insert(tk.END, f"     申报周期: {filing_period}\n", "normal")
                    text_widget.insert(tk.END, f"     截止日期: 每期{deadline_day}日\n", "normal")
                    
                    if last_filed_date:
                        text_widget.insert(tk.END, f"     最后申报: {last_filed_date}\n", "normal")
                        
                        # 计算下次申报时间
                        next_date = self.calculate_next_filing_date(
                            last_filed_date, filing_period, deadline_day
                        )
                        
                        if next_date:
                            # 计算剩余天数
                            days_left = (next_date - today).days
                            
                            text_widget.insert(tk.END, f"     下次申报: {next_date.strftime('%Y-%m-%d')}", "normal")
                            
                            if days_left < 0:
                                text_widget.insert(tk.END, f" (已逾期 {abs(days_left)} 天)", "overdue")
                            elif days_left == 0:
                                text_widget.insert(tk.END, " (今天截止!)", "overdue")
                            elif days_left <= 3:
                                text_widget.insert(tk.END, f" (还剩 {days_left} 天)", "overdue")
                            elif days_left <= 7:
                                text_widget.insert(tk.END, f" (还剩 {days_left} 天)", "warning")
                            else:
                                text_widget.insert(tk.END, f" (还剩 {days_left} 天)", "normal")
                            
                            text_widget.insert(tk.END, "\n", "normal")
                    else:
                        text_widget.insert(tk.END, f"     最后申报: 未申报\n", "warning")
                        text_widget.insert(tk.END, f"     下次申报: 请先更新最后申报时间\n", "warning")
                    
                    text_widget.insert(tk.END, "\n", "normal")
        
        # 禁止编辑
        text_widget.config(state=tk.DISABLED)
        
        # 关闭按钮
        btn_frame = tk.Frame(dialog, bg="#0f1419", pady=15)
        btn_frame.pack()
        
        tk.Button(
            btn_frame,
            text="✖ 关闭",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            relief=tk.FLAT,
            padx=40,
            pady=10,
            command=dialog.destroy
        ).pack()
    
    def calculate_next_filing_date(self, last_filed_date_str, filing_period, deadline_day):
        """计算下次申报日期"""
        try:
            last_date = datetime.strptime(last_filed_date_str, "%Y-%m-%d").date()
            
            if filing_period == "月报":
                # 下个月
                if last_date.month == 12:
                    next_year = last_date.year + 1
                    next_month = 1
                else:
                    next_year = last_date.year
                    next_month = last_date.month + 1
                
                # 确保日期有效
                try:
                    next_date = date(next_year, next_month, deadline_day)
                except ValueError:
                    # 如果该月没有这么多天，使用月末
                    if next_month == 12:
                        next_date = date(next_year, next_month, 31)
                    else:
                        next_date = date(next_year, next_month + 1, 1) - timedelta(days=1)
                
                return next_date
            
            elif filing_period == "季报":
                # 下一季度（3个月后）
                next_month = last_date.month + 3
                next_year = last_date.year
                
                if next_month > 12:
                    next_month -= 12
                    next_year += 1
                
                try:
                    next_date = date(next_year, next_month, deadline_day)
                except ValueError:
                    if next_month == 12:
                        next_date = date(next_year, next_month, 31)
                    else:
                        next_date = date(next_year, next_month + 1, 1) - timedelta(days=1)
                
                return next_date
            
            elif filing_period == "年报":
                # 下一年
                next_year = last_date.year + 1
                
                try:
                    next_date = date(next_year, last_date.month, deadline_day)
                except ValueError:
                    next_date = date(next_year, last_date.month + 1, 1) - timedelta(days=1)
                
                return next_date
            
        except Exception as e:
            print(f"计算下次申报日期错误: {e}")
            return None
        
        return None
    
    def start_reminder_thread(self):
        """启动报税提醒检查线程"""
        def check_reminders():
            while True:
                try:
                    today = date.today()
                    # 每天早上9点检查
                    if datetime.now().hour == 9 and datetime.now().minute == 0:
                        # 检查是否是月初（1-5日）
                        if 1 <= today.day <= 5:
                            self.send_tax_reminders()
                except Exception as e:
                    print(f"提醒检查错误: {e}")
                
                # 每小时检查一次
                time.sleep(3600)
        
        thread = threading.Thread(target=check_reminders, daemon=True)
        thread.start()
    
    def send_tax_reminders(self):
        """发送报税提醒"""
        today = date.today()
        current_month = today.month
        
        # 获取所有需要在本月申报的税种
        self.cursor.execute("""
            SELECT c.name, t.tax_name, t.filing_period, t.deadline_day
            FROM tax_types t
            JOIN companies c ON t.company_id = c.id
        """)
        
        tax_items = self.cursor.fetchall()
        reminder_count = 0
        
        for company_name, tax_name, filing_period, deadline_day in tax_items:
            should_remind = False
            
            if filing_period == "月报":
                should_remind = True
            elif filing_period == "季报" and current_month in [1, 4, 7, 10]:
                should_remind = True
            elif filing_period == "年报" and current_month == 1:
                should_remind = True
            
            if should_remind and today.day <= deadline_day:
                self.show_windows_notification(
                    f"报税提醒 - {company_name}",
                    f"税种: {tax_name}\n申报周期: {filing_period}\n截止日期: {deadline_day}日"
                )
                reminder_count += 1
                time.sleep(2)  # 避免通知过快
        
        if reminder_count > 0:
            # 记录提醒日志
            self.cursor.execute("""
                INSERT INTO reminder_logs (company_id, tax_type_id, remind_date, status)
                VALUES (NULL, NULL, ?, '已发送')
            """, (today.strftime("%Y-%m-%d"),))
            self.conn.commit()
    
    def show_windows_notification(self, title, message):
        """显示Windows系统通知"""
        try:
            notification.notify(
                title=title,
                message=message,
                app_name="自企所得税税种记录器",
                timeout=10
            )
        except Exception as e:
            print(f"通知发送失败: {e}")
    
    def test_reminder(self):
        """测试提醒功能"""
        self.show_windows_notification(
            "测试提醒 - 自企所得税税种记录器",
            "这是一条测试通知\n报税提醒功能正常工作！"
        )
        self.status_label.config(text="已发送测试通知")
    
    def sync_ntp_time(self):
        """同步NTP时间"""
        ntp_servers = [
            'ntp.ntsc.ac.cn',      # 国家授时中心
            'ntp.aliyun.com',      # 阿里云NTP
            'cn.ntp.org.cn',       # 中国NTP
            'time.windows.com'     # 微软NTP
        ]
        
        for server in ntp_servers:
            try:
                ntp_client = ntplib.NTPClient()
                response = ntp_client.request(server, version=3, timeout=3)
                
                # 计算时间偏移
                ntp_time = datetime.fromtimestamp(response.tx_time)
                local_time = datetime.now()
                self.ntp_offset = (ntp_time - local_time).total_seconds()
                
                self.use_ntp = True
                self.ntp_server_used = server
                print(f"NTP时间同步成功 (服务器: {server})，偏移: {self.ntp_offset:.2f}秒")
                return True
            except Exception as e:
                print(f"NTP服务器 {server} 连接失败: {e}")
                continue
        
        print("所有NTP服务器均连接失败，使用本地时间")
        self.use_ntp = False
        self.ntp_server_used = None
        return False
    
    def start_ntp_sync(self):
        """启动NTP时间同步线程"""
        def sync_thread():
            # 立即同步一次
            self.sync_ntp_time()
            
            # 每小时同步一次
            while True:
                time.sleep(3600)  # 1小时
                self.sync_ntp_time()
        
        thread = threading.Thread(target=sync_thread, daemon=True)
        thread.start()
    
    def get_current_time(self):
        """获取当前时间（NTP校准后）"""
        local_time = datetime.now()
        if self.use_ntp:
            return local_time + timedelta(seconds=self.ntp_offset)
        return local_time
    
    def update_time_display(self):
        """更新时间显示"""
        try:
            current_time = self.get_current_time()
            time_str = current_time.strftime("%Y年%m月%d日 %H:%M:%S")
            weekday = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"][current_time.weekday()]
            
            if self.use_ntp and hasattr(self, 'ntp_server_used') and self.ntp_server_used:
                if self.ntp_server_used == 'ntp.ntsc.ac.cn':
                    time_str = f"🕒 {time_str} {weekday} (国家授时中心)"
                else:
                    time_str = f"🕒 {time_str} {weekday} (NTP同步)"
            else:
                time_str = f"🕒 {time_str} {weekday} (本地时间)"
            
            self.time_label.config(text=time_str)
        except Exception as e:
            print(f"更新时间显示错误: {e}")
        
        # 每秒更新一次
        self.root.after(1000, self.update_time_display)
    
    def generate_key_from_password(self, password):
        """从密码生成加密密钥"""
        # 使用 SHA256 生成固定长度的密钥
        key = hashlib.sha256(password.encode()).digest()
        return base64.urlsafe_b64encode(key)
    
    def hash_password(self, password):
        """对密码进行哈希"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def load_password_data(self):
        """加载密码数据"""
        if not os.path.exists(self.password_file):
            return None
        
        try:
            with open(self.password_file, 'rb') as f:
                encrypted_data = f.read()
            return encrypted_data
        except Exception as e:
            print(f"读取密码文件错误: {e}")
            return None
    
    def save_password_data(self, master_password_hash, tax_passwords):
        """保存密码数据"""
        try:
            # 准备数据
            data = {
                'master_hash': master_password_hash,
                'passwords': tax_passwords
            }
            
            # 转换为 JSON
            json_data = json.dumps(data)
            
            # 使用主密码加密
            key = self.generate_key_from_password(master_password_hash)
            fernet = Fernet(key)
            encrypted_data = fernet.encrypt(json_data.encode())
            
            # 写入文件
            with open(self.password_file, 'wb') as f:
                f.write(encrypted_data)
            
            return True
        except Exception as e:
            print(f"保存密码文件错误: {e}")
            return False
    
    def decrypt_password_data(self, encrypted_data, master_password):
        """解密密码数据"""
        try:
            master_hash = self.hash_password(master_password)
            key = self.generate_key_from_password(master_hash)
            fernet = Fernet(key)
            
            decrypted_data = fernet.decrypt(encrypted_data)
            data = json.loads(decrypted_data.decode())
            
            # 验证主密码
            if data['master_hash'] != master_hash:
                return None
            
            return data
        except Exception as e:
            print(f"解密失败: {e}")
            return None
    
    def open_password_manager(self):
        """打开密码管理器"""
        encrypted_data = self.load_password_data()
        
        if encrypted_data is None:
            # 第一次使用，需要设置主密码
            self.setup_master_password()
        else:
            # 需要验证主密码
            self.verify_and_open_password_manager(encrypted_data)
    
    def setup_master_password(self):
        """设置主密码（第一次）"""
        dialog = tk.Toplevel(self.root)
        dialog.title("设置主密码")
        dialog.geometry("450x350")
        dialog.configure(bg="#1a2332")
        dialog.transient(self.root)
        dialog.grab_set()
        dialog.resizable(False, False)
        
        # 标题
        tk.Label(
            dialog,
            text="🔐 首次使用 - 设置主密码",
            font=("Microsoft YaHei UI", 14, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).pack(pady=20)
        
        tk.Label(
            dialog,
            text="请设置主密码，用于保护税务局密码\n注意：主密码一旦设置后不可修改！",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#ffa502",
            justify=tk.CENTER
        ).pack(pady=10)
        
        # 输入框
        form_frame = tk.Frame(dialog, bg="#1a2332")
        form_frame.pack(pady=20)
        
        tk.Label(
            form_frame,
            text="主密码:",
            font=("Microsoft YaHei UI", 11),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=0, column=0, padx=10, pady=10, sticky=tk.E)
        
        password_entry = tk.Entry(
            form_frame,
            font=("Microsoft YaHei UI", 11),
            bg="#0f1419",
            fg="#ffffff",
            show="•",
            width=20
        )
        password_entry.grid(row=0, column=1, padx=10, pady=10)
        
        tk.Label(
            form_frame,
            text="确认密码:",
            font=("Microsoft YaHei UI", 11),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=1, column=0, padx=10, pady=10, sticky=tk.E)
        
        confirm_entry = tk.Entry(
            form_frame,
            font=("Microsoft YaHei UI", 11),
            bg="#0f1419",
            fg="#ffffff",
            show="•",
            width=20
        )
        confirm_entry.grid(row=1, column=1, padx=10, pady=10)
        
        def confirm_setup():
            password = password_entry.get()
            confirm = confirm_entry.get()
            
            if not password:
                messagebox.showerror("错误", "请输入主密码！")
                return
            
            if len(password) < 6:
                messagebox.showerror("错误", "主密码长度至少 6 位！")
                return
            
            if password != confirm:
                messagebox.showerror("错误", "两次密码输入不一致！")
                return
            
            # 保存主密码
            master_hash = self.hash_password(password)
            if self.save_password_data(master_hash, {}):
                messagebox.showinfo("成功", "主密码设置成功！\n请妥善保管，不可找回！")
                dialog.destroy()
                # 打开密码管理器
                self.show_password_manager(master_hash, {})
            else:
                messagebox.showerror("错误", "设置主密码失败！")
        
        # 按钮
        btn_frame = tk.Frame(dialog, bg="#1a2332")
        btn_frame.pack(pady=20)
        
        tk.Button(
            btn_frame,
            text="✔ 确认",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            padx=30,
            pady=8,
            command=confirm_setup
        ).pack(side=tk.LEFT, padx=10)
        
        tk.Button(
            btn_frame,
            text="✖ 取消",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            padx=30,
            pady=8,
            command=dialog.destroy
        ).pack(side=tk.LEFT, padx=10)
    
    def verify_and_open_password_manager(self, encrypted_data):
        """验证主密码并打开密码管理器"""
        dialog = tk.Toplevel(self.root)
        dialog.title("验证主密码")
        dialog.geometry("400x230")
        dialog.configure(bg="#1a2332")
        dialog.transient(self.root)
        dialog.grab_set()
        dialog.resizable(False, False)
        
        tk.Label(
            dialog,
            text="🔒 请输入主密码",
            font=("Microsoft YaHei UI", 13, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).pack(pady=20)
        
        password_entry = tk.Entry(
            dialog,
            font=("Microsoft YaHei UI", 12),
            bg="#0f1419",
            fg="#ffffff",
            show="•",
            width=25
        )
        password_entry.pack(pady=10)
        password_entry.focus()
        
        def verify():
            password = password_entry.get()
            if not password:
                messagebox.showerror("错误", "请输入密码！")
                return
            
            data = self.decrypt_password_data(encrypted_data, password)
            if data:
                dialog.destroy()
                self.show_password_manager(data['master_hash'], data['passwords'])
            else:
                messagebox.showerror("错误", "主密码错误！")
                password_entry.delete(0, tk.END)
        
        # 按回车键也可以验证
        password_entry.bind('<Return>', lambda e: verify())
        
        btn_frame = tk.Frame(dialog, bg="#1a2332")
        btn_frame.pack(pady=20)
        
        tk.Button(
            btn_frame,
            text="✔ 确认",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            padx=30,
            pady=8,
            command=verify
        ).pack(side=tk.LEFT, padx=10)
        
        tk.Button(
            btn_frame,
            text="✖ 取消",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            padx=30,
            pady=8,
            command=dialog.destroy
        ).pack(side=tk.LEFT, padx=10)
    
    def show_password_manager(self, master_hash, tax_passwords):
        """显示密码管理器"""
        dialog = tk.Toplevel(self.root)
        dialog.title("电子税务局密码管理")
        dialog.geometry("700x500")
        dialog.configure(bg="#0f1419")
        dialog.transient(self.root)
        
        # 标题
        title_frame = tk.Frame(dialog, bg="#1a2332", pady=15)
        title_frame.pack(fill=tk.X)
        
        tk.Label(
            title_frame,
            text="🔐 电子税务局密码管理",
            font=("Microsoft YaHei UI", 15, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).pack()
        
        # 获取所有公司
        self.cursor.execute("SELECT id, name FROM companies ORDER BY name")
        companies = self.cursor.fetchall()
        
        # 内容区域
        content_frame = tk.Frame(dialog, bg="#0f1419")
        content_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 创建滚动画布
        canvas = tk.Canvas(content_frame, bg="#0f1419", highlightthickness=0)
        scrollbar = ttk.Scrollbar(content_frame, orient="vertical", command=canvas.yview)
        scrollable_frame = tk.Frame(canvas, bg="#0f1419")
        
        scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )
        
        canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)
        
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 密码输入框字典
        password_entries = {}
        
        if not companies:
            tk.Label(
                scrollable_frame,
                text="⚠️ 暂无公司，请先添加公司",
                font=("Microsoft YaHei UI", 11),
                bg="#0f1419",
                fg="#ffa502"
            ).pack(pady=50)
        else:
            for company_id, company_name in companies:
                # 公司框架
                company_frame = tk.LabelFrame(
                    scrollable_frame,
                    text=f"🏢 {company_name}",
                    font=("Microsoft YaHei UI", 11, "bold"),
                    bg="#1a2332",
                    fg="#00d4ff",
                    padx=15,
                    pady=10
                )
                company_frame.pack(fill=tk.X, pady=10)
                
                # 账号
                tk.Label(
                    company_frame,
                    text="账号:",
                    font=("Microsoft YaHei UI", 10),
                    bg="#1a2332",
                    fg="#ffffff"
                ).grid(row=0, column=0, sticky=tk.W, pady=5)
                
                username_entry = tk.Entry(
                    company_frame,
                    font=("Microsoft YaHei UI", 10),
                    bg="#0f1419",
                    fg="#ffffff",
                    width=30
                )
                username_entry.grid(row=0, column=1, padx=10, pady=5)
                
                # 密码
                tk.Label(
                    company_frame,
                    text="密码:",
                    font=("Microsoft YaHei UI", 10),
                    bg="#1a2332",
                    fg="#ffffff"
                ).grid(row=1, column=0, sticky=tk.W, pady=5)
                
                password_entry = tk.Entry(
                    company_frame,
                    font=("Microsoft YaHei UI", 10),
                    bg="#0f1419",
                    fg="#ffffff",
                    width=30
                )
                password_entry.grid(row=1, column=1, padx=10, pady=5)
                
                # 加载已保存的密码
                company_key = str(company_id)
                if company_key in tax_passwords:
                    username_entry.insert(0, tax_passwords[company_key].get('username', ''))
                    password_entry.insert(0, tax_passwords[company_key].get('password', ''))
                
                password_entries[company_id] = {
                    'username': username_entry,
                    'password': password_entry
                }
        
        # 按钮区域
        btn_frame = tk.Frame(dialog, bg="#0f1419", pady=15)
        btn_frame.pack()
        
        def save_passwords():
            # 收集所有密码
            new_passwords = {}
            for company_id, entries in password_entries.items():
                username = entries['username'].get().strip()
                password = entries['password'].get().strip()
                if username or password:
                    new_passwords[str(company_id)] = {
                        'username': username,
                        'password': password
                    }
            
            # 保存
            if self.save_password_data(master_hash, new_passwords):
                messagebox.showinfo("成功", "密码保存成功！")
                dialog.destroy()
            else:
                messagebox.showerror("错误", "保存失败！")
        
        tk.Button(
            btn_frame,
            text="💾 保存",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            padx=40,
            pady=10,
            command=save_passwords
        ).pack(side=tk.LEFT, padx=10)
        
        tk.Button(
            btn_frame,
            text="✖ 关闭",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            padx=40,
            pady=10,
            command=dialog.destroy
        ).pack(side=tk.LEFT, padx=10)
    
    def open_order_manager(self):
        """打开责令书管理器"""
        dialog = tk.Toplevel(self.root)
        dialog.title("责令书管理")
        dialog.geometry("1000x650")
        dialog.configure(bg="#0f1419")
        dialog.transient(self.root)
        
        title_frame = tk.Frame(dialog, bg="#1a2332", pady=15)
        title_frame.pack(fill=tk.X)
        
        tk.Label(
            title_frame,
            text="📋 责令限期改正管理",
            font=("Microsoft YaHei UI", 16, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).pack()
        
        content_frame = tk.Frame(dialog, bg="#0f1419")
        content_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        list_frame = tk.Frame(content_frame, bg="#1a2332", relief=tk.RIDGE, bd=2)
        list_frame.pack(fill=tk.BOTH, expand=True)
        
        columns = ("公司名称", "责令书编号", "下达日期", "限期日期", "状态")
        order_tree = ttk.Treeview(list_frame, columns=columns, show="tree headings", height=18)
        
        order_tree.column("#0", width=50)
        order_tree.heading("#0", text="ID")
        
        for col in columns:
            order_tree.column(col, width=150, anchor=tk.CENTER)
            order_tree.heading(col, text=col)
        
        scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=order_tree.yview)
        order_tree.configure(yscrollcommand=scrollbar.set)
        
        order_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        def load_orders():
            for item in order_tree.get_children():
                order_tree.delete(item)
            
            self.cursor.execute("""
                SELECT co.id, c.name, co.order_number, co.issue_date, 
                       co.deadline_date, co.status
                FROM correction_orders co
                JOIN companies c ON co.company_id = c.id
                ORDER BY co.deadline_date DESC
            """)
            
            orders = self.cursor.fetchall()
            for order in orders:
                order_tree.insert("", tk.END, text=order[0], values=order[1:])
        
        load_orders()
        
        btn_frame = tk.Frame(dialog, bg="#0f1419", pady=15)
        btn_frame.pack()
        
        def add_order():
            self.show_order_editor(None, load_orders)
        
        def edit_order():
            selection = order_tree.selection()
            if not selection:
                messagebox.showwarning("警告", "请先选择要编辑的责令书！")
                return
            
            item = order_tree.item(selection[0])
            order_id = item['text']
            self.show_order_editor(order_id, load_orders)
        
        def delete_order():
            selection = order_tree.selection()
            if not selection:
                messagebox.showwarning("警告", "请先选择要删除的责令书！")
                return
            
            item = order_tree.item(selection[0])
            order_id = item['text']
            company_name = item['values'][0]
            
            if messagebox.askyesno("确认删除", f"确定要删除 {company_name} 的责令书记录吗？"):
                self.cursor.execute("DELETE FROM correction_orders WHERE id=?", (order_id,))
                self.conn.commit()
                messagebox.showinfo("成功", "责令书记录已删除！")
                load_orders()
        
        def go_to_website():
            webbrowser.open("http://hebei.chinatax.gov.cn/hbsw/index.html")
        
        tk.Button(
            btn_frame,
            text="➕ 添加责令书",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            padx=20,
            pady=10,
            command=add_order
        ).pack(side=tk.LEFT, padx=5)
        
        tk.Button(
            btn_frame,
            text="✏ 编辑",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ffa502",
            fg="#000000",
            cursor="hand2",
            padx=20,
            pady=10,
            command=edit_order
        ).pack(side=tk.LEFT, padx=5)
        
        tk.Button(
            btn_frame,
            text="🗑 删除",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            padx=20,
            pady=10,
            command=delete_order
        ).pack(side=tk.LEFT, padx=5)
        
        tk.Button(
            btn_frame,
            text="👉 去办理",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#26de81",
            fg="#000000",
            cursor="hand2",
            padx=20,
            pady=10,
            command=go_to_website
        ).pack(side=tk.LEFT, padx=5)
        
        tk.Button(
            btn_frame,
            text="✖ 关闭",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#6c5ce7",
            fg="#ffffff",
            cursor="hand2",
            padx=20,
            pady=10,
            command=dialog.destroy
        ).pack(side=tk.LEFT, padx=5)
    
    def show_order_editor(self, order_id, reload_callback):
        """显示责令书编辑器"""
        dialog = tk.Toplevel(self.root)
        dialog.title("添加责令书" if not order_id else "编辑责令书")
        dialog.geometry("650x650")
        dialog.configure(bg="#1a2332")
        dialog.transient(self.root)
        dialog.grab_set()
        dialog.resizable(False, False)
        
        self.cursor.execute("SELECT id, name FROM companies ORDER BY name")
        companies = self.cursor.fetchall()
        
        if not companies:
            messagebox.showerror("错误", "请先添加公司！")
            dialog.destroy()
            return
        
        tk.Label(
            dialog,
            text="📋 " + ("添加责令书" if not order_id else "编辑责令书"),
            font=("Microsoft YaHei UI", 14, "bold"),
            bg="#1a2332",
            fg="#00d4ff"
        ).pack(pady=15)
        
        form_frame = tk.Frame(dialog, bg="#1a2332", padx=30)
        form_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        tk.Label(
            form_frame,
            text="选择公司*:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=0, column=0, sticky=tk.W, pady=10)
        
        company_var = tk.StringVar()
        company_combo = ttk.Combobox(
            form_frame,
            textvariable=company_var,
            values=[f"{c[0]}:{c[1]}" for c in companies],
            state="readonly",
            font=("Microsoft YaHei UI", 10),
            width=35
        )
        company_combo.grid(row=0, column=1, pady=10)
        
        tk.Label(
            form_frame,
            text="责令书编号*:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=1, column=0, sticky=tk.W, pady=10)
        
        order_number_entry = tk.Entry(
            form_frame,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            width=38
        )
        order_number_entry.grid(row=1, column=1, pady=10)
        
        tk.Label(
            form_frame,
            text="下达日期*:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=2, column=0, sticky=tk.W, pady=10)
        
        issue_date_entry = tk.Entry(
            form_frame,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            width=38
        )
        issue_date_entry.grid(row=2, column=1, pady=10)
        issue_date_entry.insert(0, datetime.now().strftime("%Y-%m-%d"))
        
        tk.Label(
            form_frame,
            text="限期日期*:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=3, column=0, sticky=tk.W, pady=10)
        
        deadline_date_entry = tk.Entry(
            form_frame,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            width=38
        )
        deadline_date_entry.grid(row=3, column=1, pady=10)
        
        tk.Label(
            form_frame,
            text="办理状态*:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=4, column=0, sticky=tk.W, pady=10)
        
        status_var = tk.StringVar(value="未办理")
        status_combo = ttk.Combobox(
            form_frame,
            textvariable=status_var,
            values=["未办理", "办理中", "已办结"],
            state="readonly",
            font=("Microsoft YaHei UI", 10),
            width=35
        )
        status_combo.grid(row=4, column=1, pady=10)
        
        tk.Label(
            form_frame,
            text="整改内容:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=5, column=0, sticky=tk.NW, pady=10)
        
        content_text = tk.Text(
            form_frame,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            width=38,
            height=6
        )
        content_text.grid(row=5, column=1, pady=10)
        
        tk.Label(
            form_frame,
            text="备注:",
            font=("Microsoft YaHei UI", 10),
            bg="#1a2332",
            fg="#00d4ff"
        ).grid(row=6, column=0, sticky=tk.NW, pady=10)
        
        notes_text = tk.Text(
            form_frame,
            font=("Microsoft YaHei UI", 10),
            bg="#0f1419",
            fg="#ffffff",
            width=38,
            height=4
        )
        notes_text.grid(row=6, column=1, pady=10)
        
        if order_id:
            self.cursor.execute("""
                SELECT company_id, order_number, issue_date, deadline_date, 
                       content, status, notes
                FROM correction_orders WHERE id=?
            """, (order_id,))
            order_data = self.cursor.fetchone()
            if order_data:
                for idx, (cid, cname) in enumerate(companies):
                    if cid == order_data[0]:
                        company_combo.current(idx)
                        break
                
                order_number_entry.insert(0, order_data[1] or "")
                issue_date_entry.delete(0, tk.END)
                issue_date_entry.insert(0, order_data[2] or "")
                deadline_date_entry.insert(0, order_data[3] or "")
                content_text.insert("1.0", order_data[4] or "")
                status_var.set(order_data[5] or "未办理")
                notes_text.insert("1.0", order_data[6] or "")
        
        btn_frame = tk.Frame(dialog, bg="#1a2332", pady=15)
        btn_frame.pack()
        
        def save_order():
            company_str = company_var.get()
            if not company_str:
                messagebox.showerror("错误", "请选择公司！")
                return
            
            company_id = int(company_str.split(":")[0])
            order_number = order_number_entry.get().strip()
            issue_date = issue_date_entry.get().strip()
            deadline_date = deadline_date_entry.get().strip()
            
            if not order_number or not issue_date or not deadline_date:
                messagebox.showerror("错误", "请填写必填项（带*号）！")
                return
            
            content = content_text.get("1.0", tk.END).strip()
            status = status_var.get()
            notes = notes_text.get("1.0", tk.END).strip()
            
            if order_id:
                self.cursor.execute("""
                    UPDATE correction_orders SET
                        company_id=?, order_number=?, issue_date=?, deadline_date=?,
                        content=?, status=?, notes=?
                    WHERE id=?
                """, (company_id, order_number, issue_date, deadline_date,
                      content, status, notes, order_id))
            else:
                self.cursor.execute("""
                    INSERT INTO correction_orders
                    (company_id, order_number, issue_date, deadline_date, content, status, notes)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                """, (company_id, order_number, issue_date, deadline_date,
                      content, status, notes))
            
            self.conn.commit()
            messagebox.showinfo("成功", "责令书保存成功！")
            reload_callback()
            dialog.destroy()
        
        tk.Button(
            btn_frame,
            text="💾 保存",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#00d4ff",
            fg="#000000",
            cursor="hand2",
            padx=30,
            pady=10,
            command=save_order
        ).pack(side=tk.LEFT, padx=10)
        
        tk.Button(
            btn_frame,
            text="✖ 取消",
            font=("Microsoft YaHei UI", 11, "bold"),
            bg="#ff4757",
            fg="#ffffff",
            cursor="hand2",
            padx=30,
            pady=10,
            command=dialog.destroy
        ).pack(side=tk.LEFT, padx=10)
    
    def on_closing(self):
        """关闭程序时的清理工作"""
        self.conn.close()
        self.root.destroy()


def main():
    root = tk.Tk()
    app = TaxRecorderApp(root)
    root.protocol("WM_DELETE_WINDOW", app.on_closing)
    root.mainloop()


if __name__ == "__main__":
    main()
